<template id="drawer-createTicket">
    <!-- 流水申请抽屉 -->
    <v-navigation-drawer class="elevation-24" v-if="isRequestDrawerShown" v-model="isRequestDrawerShown" :permanent="isRequestDrawerShown" fixed temporary right width="80%">
        <v-form ref="createForm" lazy-validation>
            <!-- 抽屉标题 -->
            <v-row>
                <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">申请信息</span>
            </v-row>
            <!-- 抽屉表单 -->
            <!-- <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.xxxId" :rules="validationRules.requireRules"></v-text-field> -->
            <v-row class="mt-0 px-4">

                <v-col cols="12" sm="12" md="4" v-if="ticketType ==='flow'">
                    <span class="jh-input-label">合同ID</span>
                    <v-text-field class="jh-v-input" dense single-line filled label="维修、保险没有合同可不填" v-model="requestActionData.ticketBizId"></v-text-field>
                </v-col>

                <v-col cols="12" sm="12" md="4" v-else>
                    <span class="jh-input-label">合同ID</span>
                    <v-text-field class="jh-v-input" dense single-line filled v-model="dispatchActionData.contractId"></v-text-field>
                </v-col>

                <v-col cols="12" sm="12" md="4" v-if="ticketType ==='flow'">
                    <span class="jh-input-label">工单类型</span>
                    <v-select class="jh-v-input" dense single-line filled v-model="requestActionData.ticketType" :items="flowType"></v-select>
                </v-col>

                <v-col cols="12" sm="12" md="4" v-else>
                    <span class="jh-input-label">工单类型</span>
                    <v-select class="jh-v-input" dense single-line filled v-model="dispatchActionData.ticketType" :items="dispatchType"></v-select>
                </v-col>

                <v-col cols="12" :class="{'pa-0': isMobile, 'px-4': isMobile, 'pt-6': isMobile}">
                    <span class="inputLabel">申请项</span>
                    <v-container class="pa-0">
                        <v-card elevation="0" outlined>
                            <!-- 收付申请表格 -->
                            <v-data-table class="elevation-0 mt-0 mb-xs-4 flex-fill d-flex flex-column" :loading="loading" :headers="headers" v-if="ticketType ==='flow'" :items="requestActionData.ticketContentRequest" hide-default-footer disable-pagination>

                                <template v-slot:item.request-type="{ item }">
                                    <v-select class="jh-v-input" dense filled single-line label="(押金、租金、服务费、维修费、保险费...)" v-model="item.requestType" :rules="requireRules" :items="requestTypeList" item-text="name" item-value="value"></v-select>
                                </template>

                                <template v-slot:item.request-amount="{ item }">
                                    <v-text-field class="jh-v-input mr-2" type="number" dense filled single-line label="申请金额" v-model="item.requestAmount">
                                    </v-text-field>
                                </template>

                                <template v-slot:item.action="{ item, index }">
                                    <span class="error--text font-weight-medium font-size-2 mr-1 mr-sm-2" role="button" small @click="doUiAction('deleteItem', {item, index})">删除</span>
                                </template>

                                <template v-slot:body.append="">
                                    <span>总金额：</span>
                                    <v-text-field class="jh-v-input" style="display: inline-block;" readonly dense single-line v-model="ticketAmount"></v-text-field>
                                </template>
                            </v-data-table>

                            <!-- 发车申请表格 -->
                            <v-data-table class="elevation-0 mt-0 mb-xs-4 flex-fill d-flex flex-column" :loading="loading" :headers="headers" v-else :items="dispatchActionData.ticketContentRequest" hide-default-footer disable-pagination>

                                <template v-slot:item.car-id="{ item }">
                                    <v-text-field class="jh-v-input mr-2" filled dense single-line label="车辆编号" v-model="item.carId" readonly>
                                    </v-text-field>
                                </template>

                                <template v-slot:item.car-number="{ item }">
                                    <v-text-field class="jh-v-input mr-2" filled dense single-line label="车牌号" v-model="item.carNumber" readonly>
                                    </v-text-field>
                                </template>

                                <template v-slot:item.current-kilometers="{ item }">
                                    <v-text-field class="jh-v-input mr-2" filled dense single-line label="目前公里数" v-model="item.currentKilometers">
                                    </v-text-field>
                                </template>

                                <template v-slot:item.dispatch-fuel="{ item }">
                                    <v-text-field class="jh-v-input mr-2" filled dense single-line label="目前燃油量" v-model="item.dispatchFuel">
                                    </v-text-field>
                                </template>


                            </v-data-table>
                        </v-card>
                        <v-btn class="add-btn" @click="doUiAction('addItem')" width="100%" v-if="ticketType==='flow'">添加申请项
                        </v-btn>
                    </v-container>
                    <v-col cols="12" sm="12" md="12">
                        <span class="jh-input-label">工单描述</span>
                        <v-textarea class="jh-v-input" dense single-line filled v-model="requestActionData.ticketDesc"></v-textarea>
                    </v-col>


                    <!-- <v-col cols="12" sm="12" md="4">
                            <span class="jh-input-label">处理描述</span>
                            <v-text-field class="jh-v-input" dense single-line filled v-model="requestActionData.ticketStatusDesc"></v-text-field>
                        </v-col> -->
            </v-col></v-row>

            <!-- 抽屉操作按钮 -->
            <v-row class="justify-end mx-0 mt-8 px-6">
                <v-btn color="success" @click="doUiAction('flowRequest')" small v-if="ticketType === 'flow'">保存</v-btn>

                <v-btn color="success" @click="doUiAction('dispatchItemCar')" small v-else>保存</v-btn>
                <v-btn class="elevation-0 ml-2" @click="doUiAction('close')" small>取消</v-btn>
            </v-row>
        </v-form>
        <!-- 抽屉关闭按钮 -->
        <v-btn class="drawer-close-float-btn" elevation="0" color="success" fab absolute top left small tile @click="doUiAction('close')">
            <v-icon>mdi-close</v-icon>
        </v-btn>
    </v-navigation-drawer>
    
</template>

<script type="module">
    Vue.component("drawer-createTicket", {
        template: '#drawer-createTicket',
        props: {
            ticketType: {
                type: String,
                default: ""
            },
            carId: {
                type: String,
                default: ""
            },
            carNumber: {
                type: String,
                default: ""
            }
        },
        data: () => ({
            // 发车/退车申请
            dispatchActionData: {},
            dispatchType: ['发车申请', '退车申请'],

            // 流水申请
            ticketAmount: 0,
            flowType: ['付款申请', '收款申请'],
            requestActionData: {},
            isRequestDrawerShown: false,
            tableData: [],
            requestTypeList: [
                { name: "押金", value: "押金" },
                { name: "管理费", value: "管理费" },
                { name: "租金", value: "租金" },
                { name: "保养费", value: "保养费" },
                { name: "维修费", value: "维修费" },
                { name: "保险费", value: "保险费" }
            ],
            requireRules: [
                v => !!v || '必填',
            ],
            headers: [
                { text: '操作', value: 'action', align: 'center', sortable: false, width: 100, class: 'fixed', cellClass: 'fixed' },
                { text: "申请类型", value: "request-type", width: 80 },
                { text: "申购金额", value: "request-amount", width: 80 },
            ],
            loading: false
        }),
        computed: {
            isMobile() {
                return window.innerWidth < 600;
            }
        },
        watch: {
            // TODO: 当其他项发生变化时，也会触发改方法，性能开销大
            'requestActionData.ticketContentRequest': {
                handler(newTableData) {

                    // let totalAmount = 0
                    // for(let index in newTableData){
                    //     // console.log("index",index)
                    //     this.$watch(
                    //         ()=>newTableData[index].requestAmount,
                    //         (newVal)=>{
                    //             console.log(newVal)
                    //             totalAmount += Number(newVal)
                    //     })
                    // }
                    if (this.ticketType === "flow") {
                        let totalAmount = 0
                        for (let row of this.requestActionData.ticketContentRequest) {
                            totalAmount += Number(row.requestAmount)
                        }
                        this.ticketAmount = totalAmount
                        // 向父组件传递总金额
                        // this.$emit("getTicketAmount", this.ticketAmount)
                    }
                },
                deep: true
            },
        },
        async created() {
        },
        async mounted() {
        },
        methods: {
            async doUiAction(uiActionId, uiActionData) {
                switch (uiActionId) {
                    case 'flowRequest':
                        await this.confirmCreateItemDialog();
                        await this.doFlowRequest();
                        await this.close()
                        break;
                    case 'dispatchItemCar':
                        await this.confirmCreateItemDialog();
                        await this.doDispatchItemCar();
                        await this.close()
                        break;
                    case 'open':
                        await this.open(uiActionData);
                        break;
                    case 'close':
                        await this.close();
                        break;
                    case 'addItem':
                        await this.doAddItem();
                        break;
                    case 'deleteItem':
                        await this.doDeleteItem(uiActionData);
                        break;
                    case 'updateTable':
                        await this.updateTable();
                        break;
                    default:
                        console.error("[doUiAction] uiActionId not find", { uiActionId });
                        break;
                }
            },
            // TODO: 报错 t.filter is not a function,但不影响执行
            // 发车申请
            async doDispatchItemCar() {
                await window.jhMask.show();
                await window.vtoast.loading("申请中");
                const ticketContentRequest = JSON.stringify(this.dispatchActionData.ticketContentRequest)
                Object.assign(this.dispatchActionData, { ticketContentRequest })
                this.dispatchActionData['ticketBizId'] = this.dispatchActionData['contractId']
                delete this.dispatchActionData.contractId
                console.log(this.dispatchActionData)
                await window.jianghuAxios({
                    data: {
                        appData: {
                            pageId: 'ticketManagement',
                            actionId: 'insertItem',
                            actionData: {
                                ...this.dispatchActionData,
                                ticketRequestByUserId: `<$ ctx.userInfo.userId $>`,
                                ticketRequestByUser: `<$ ctx.userInfo.username $>`,
                                ticketRequestAt: dayjs().format("YYYY-MM-DD hh:mm:ss")
                            },
                            idGenerate: {
                                type: "idSequence",
                                prefix: "GD",
                                bizId: "ticketId",
                                tableName: "ticket",
                            },
                        }
                    }
                })
                await window.jhMask.hide();
                await window.vtoast.success("申请成功");
            },
            // 开始申请流水
            async doFlowRequest() {
                await window.jhMask.show();
                await window.vtoast.loading("流水申请中");
                const ticketContentRequest = JSON.stringify(this.requestActionData.ticketContentRequest)
                Object.assign(this.requestActionData, { ticketContentRequest })
                await window.jianghuAxios({
                    data: {
                        appData: {
                            pageId: 'ticketManagement',
                            actionId: 'insertItem',
                            actionData: {
                                ...this.requestActionData,
                                ticketAmount: this.ticketAmount,
                                ticketRequestByUserId: `<$ ctx.userInfo.userId $>`,
                                ticketRequestByUser: `<$ ctx.userInfo.username $>`,
                                ticketRequestAt: dayjs().format("YYYY-MM-DD hh:mm:ss")
                            },
                            idGenerate: {
                                type: "idSequence",
                                prefix: "GD",
                                bizId: "ticketId",
                                tableName: "ticket",
                            }
                        }
                    }
                })
                await window.jhMask.hide();
                await window.vtoast.success("流水申请成功");
            },
            async confirmCreateItemDialog() {
                if (await window.confirmDialog({ title: "新增", content: "确定新增吗？" }) === false) {
                    throw new Error("[confirmCreateFormDialog] 否");
                }
            },
            async open(uiActionData) {
                this.isRequestDrawerShown = true

                if (this.ticketType === "flow") {
                    this.requestActionData = {
                        ...uiActionData,
                        ticketContentRequest: []
                    }
                } else {
                    this.dispatchActionData = {
                        ...uiActionData,
                        ticketContentRequest: []
                    }
                    // 修改标题头
                    this.doUiAction("updateTable")
                }
            },
            async close() {
                this.isRequestDrawerShown = false;
            },
            async updateTable() {
                // 表头设置为空数组
                this.headers = []
                this.headers.push(
                    { text: "车辆编号", value: "car-id", width: 80 },
                    { text: "车牌号", value: "car-number", width: 80 },
                    { text: "燃油量", value: "dispatch-fuel", width: 80 },
                    { text: "目前公里数", value: "current-kilometers", width: 80 }
                )

                this.dispatchActionData.ticketContentRequest.push({
                    carId: this.carId,
                    carNumber: this.carNumber,
                    dispatchFuel: null,
                    currentKilometers: null
                });
                this.$emit("input", [...this.dispatchActionData.ticketContentRequest]);
            },

            async doAddItem() {
                // 添加申请信息
                this.requestActionData.ticketContentRequest.push({
                    requestType: null,
                    requestAmount: null
                });
                this.$emit("input", [...this.requestActionData.ticketContentRequest]);
                // console.log(this.tableData)
            },
            async doDeleteItem({ index }) {
                // console.log("index", index)
                // let list = _.deepClone(this.tableData);
                // console.log("beforeList",list)
                this.requestActionData.ticketContentRequest.splice(index, 1);
                // console.log("afterList",list)
                this.$emit("input", this.requestActionData.ticketContentRequest);
                this.$emit("change", this.requestActionData.ticketContentRequest);
            },
        }
    })
</script>